<template>
  <div class="login-container">
    <el-card class="login-card">
      <h2>{{ t('login.title') }}</h2>
      <el-form :model="loginForm" :rules="rules" ref="loginFormRef" label-width="100px">
        <el-form-item :label="t('login.username')" prop="username">
          <el-input v-model="loginForm.username" :placeholder="t('login.enterUsername')"></el-input>
        </el-form-item>
        <el-form-item :label="t('login.password')" prop="password">
          <el-input 
            v-model="loginForm.password" 
            type="password" 
            :placeholder="t('login.enterPassword')"
            @keyup.enter="handleLogin"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button 
            type="primary" 
            @click="handleLogin" 
            :loading="loading"
            style="width: 100%"
          >
            {{ t('login.loginButton') }}
          </el-button>
        </el-form-item>
      </el-form>
      <div class="register-link">
        <p>{{ t('login.noAccount') }} <router-link to="/register">{{ t('login.registerHere') }}</router-link></p>
      </div>
    </el-card>
  </div>
</template>

<script>
import { ElMessage } from 'element-plus'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import { ref, reactive } from 'vue'
import { useI18n } from 'vue-i18n'
import { nextTick } from 'vue'

export default {
  name: 'LoginPage',
  setup() {
    const store = useStore()
    const router = useRouter()
    const { t } = useI18n()
    const loading = ref(false)
    
    const loginForm = reactive({
      username: '',
      password: ''
    })
    
    const rules = {
      username: [
        { required: true, message: t('login.enterUsername'), trigger: 'blur' }
      ],
      password: [
        { required: true, message: t('login.enterPassword'), trigger: 'blur' },
        { min: 6, message: t('login.passwordMinLength'), trigger: 'blur' }
      ]
    }
    
    const handleLogin = async () => {
      try {
        loading.value = true
        console.log('Login form data:', loginForm);
        
        // 使用Promise.race设置超时，避免无限等待
        const loginPromise = store.dispatch('login', {
          username: loginForm.username,
          password: loginForm.password
        });
        
        // 创建一个超时Promise
        const timeoutPromise = new Promise((_, reject) => 
          setTimeout(() => reject(new Error('Login request timeout')), 10000)
        );
        
        // 使用Promise.race来确保请求不会无限期等待
        const result = await Promise.race([loginPromise, timeoutPromise]);
        
        console.log('Login result:', result);
        
        if (result && result.success) {
          ElMessage.success(t('login.loginSuccess'))
          
          // 确保状态完全更新和持久化
          await nextTick();
          await new Promise(resolve => setTimeout(resolve, 800)); // 增加延迟时间
          
          // 立即检查store状态以确保已更新
          const updatedToken = store.state.token;
          const updatedUser = store.state.user;
          const updatedRole = store.state.role;
          
          if (updatedToken && updatedUser && updatedRole && result.token && result.user) {
            // 再次确认localStorage状态同步
            await new Promise(resolve => setTimeout(resolve, 200));
            
            // 确保在跳转前，认证状态为true
            const updatedIsAuthenticated = store.state.isAuthenticated;
            
            if (updatedIsAuthenticated) {
              // Redirect based on user role
              if (updatedRole === 'ADMIN') {
                console.log('Redirecting to admin dashboard');
                router.push('/admin/dashboard');
              } else {
                console.log('Redirecting to merchant dashboard');
                router.push('/merchant');
              }
            } else {
              ElMessage.error(t('login.stateUpdateError'));
            }
          } else {
            // 如果状态未正确更新，显示错误
            ElMessage.error(t('login.stateUpdateError'));
          }
        } else {
          ElMessage.error(result?.message || t('login.loginFailed'))
        }
      } catch (error) {
        console.error('Login error:', error);
        // 检查是否是超时错误
        if (error.message === 'Login request timeout') {
          ElMessage.error('登录请求超时，请稍后重试');
        } else {
          ElMessage.error(error.response?.data?.message || t('login.errorOccurred'));
        }
      } finally {
        loading.value = false
      }
    }
    
    return {
      loginForm,
      rules,
      loading,
      handleLogin,
      t
    }
  }
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f0f2f5;
}

.login-card {
  width: 400px;
  padding: 20px;
}

.register-link {
  margin-top: 20px;
  text-align: center;
}

.register-link a {
  color: #409EFF;
  text-decoration: none;
}
</style>